package weichat

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/base64"
	"encoding/json"
	"errors"
	"main.go/shttps"
)

//逻辑处理
var (
	ErrAppIDNotMatch       = errors.New("app id not match")
	ErrInvalidBlockSize    = errors.New("invalid block size")
	ErrInvalidPKCS7Data    = errors.New("invalid PKCS7 data")
	ErrInvalidPKCS7Padding = errors.New("invalid padding on input")
)

//定义返回的用户结构
type WxUserInfo struct {
	OpenID    string `json:"openId"`
	UnionID   string `json:"unionId"`
	NickName  string `json:"nickName"`
	Gender    int    `json:"gender"`
	City      string `json:"city"`
	Province  string `json:"province"`
	Country   string `json:"country"`
	AvatarURL string `json:"avatarUrl"`
	Language  string `json:"language"`
	Watermark struct {
		Timestamp int64  `json:"timestamp"`
		AppID     string `json:"appid"`
	} `json:"watermark"`
}

//定义返回的用户手机号信息
type WxUserPhone struct {
	PhoneNumber string `json:"phoneNumber"`
	PurePhoneNumber string `json:"purePhoneNumber"`
	CountryCode string `json:"countryCode"`
	Watermark struct {
		Timestamp int64  `json:"timestamp"`
		AppID     string `json:"appid"`
	} `json:"watermark"`
}

type WXUserDataCrypt struct {
	appID, sessionKey string
}

func NewWXUserDataCrypt(appID, sessionKey string) *WXUserDataCrypt {
	return &WXUserDataCrypt{
		appID:      appID,
		sessionKey: sessionKey,
	}
}

// pkcs7Unpad returns slice of the original data without padding
func pkcs7Unpad(data []byte, blockSize int) ([]byte, error) {
	if blockSize <= 0 {
		return nil, ErrInvalidBlockSize
	}
	if len(data)%blockSize != 0 || len(data) == 0 {
		return nil, ErrInvalidPKCS7Data
	}
	c := data[len(data)-1]
	n := int(c)
	if n == 0 || n > len(data) {
		return nil, ErrInvalidPKCS7Padding
	}
	for i := 0; i < n; i++ {
		if data[len(data)-n+i] != c {
			return nil, ErrInvalidPKCS7Padding
		}
	}
	return data[:len(data)-n], nil
}
//只解密用户信息
func (w *WXUserDataCrypt) DecryptUserinfo(encryptedData, iv string) (*WxUserInfo, error) {
	aesKey, err := base64.StdEncoding.DecodeString(w.sessionKey)
	if err != nil {
		return nil, err
	}
	cipherText, err := base64.StdEncoding.DecodeString(encryptedData)
	if err != nil {
		return nil, err
	}
	ivBytes, err := base64.StdEncoding.DecodeString(iv)
	if err != nil {
		return nil, err
	}
	block, err := aes.NewCipher(aesKey)
	if err != nil {
		return nil, err
	}
	mode := cipher.NewCBCDecrypter(block, ivBytes)
	mode.CryptBlocks(cipherText, cipherText)
	cipherText, err = pkcs7Unpad(cipherText, block.BlockSize())
	if err != nil {
		return nil, err
	}

	userInfo:=new(WxUserInfo)
	err = json.Unmarshal(cipherText, userInfo)
	if err != nil {
		return nil, err
	}
	if userInfo.Watermark.AppID != w.appID {
		return nil, ErrAppIDNotMatch
	}
	return userInfo, nil
}
//解密encryptedData信息
func (w *WXUserDataCrypt) Decrypt(encryptedData, iv string) (interface{}, error) {
	aesKey, err := base64.StdEncoding.DecodeString(w.sessionKey)
	if err != nil {
		return nil, err
	}
	cipherText, err := base64.StdEncoding.DecodeString(encryptedData)
	if err != nil {
		return nil, err
	}
	ivBytes, err := base64.StdEncoding.DecodeString(iv)
	if err != nil {
		return nil, err
	}
	block, err := aes.NewCipher(aesKey)
	if err != nil {
		return nil, err
	}
	mode := cipher.NewCBCDecrypter(block, ivBytes)
	mode.CryptBlocks(cipherText, cipherText)
	cipherText, err = pkcs7Unpad(cipherText, block.BlockSize())
	if err != nil {
		return nil, err
	}

	info:=new(interface{})
	err = json.Unmarshal(cipherText, info)
	if err != nil {
		return nil, err
	}
	//if wxUserPhone.Watermark.AppID != w.appID {
	//	return nil, ErrAppIDNotMatch
	//}
	return info, nil
}


//检查一段文本是否含有违法违规内容 请求参数
type CheckStructReq struct {

	Version string `json:"version"`
	Openid string `json:"openid"`
	Scene int `json:"scene"`
	Content string `json:"content"`
	Nickname string `json:"nickname"`
	Title string `json:"title"`
	Signature string `json:"signature"`
}

//获取唯一凭证
type AccessTokenRes struct {
	AccessToken string `json:"access_token"`
	ExpiresIn int64 `json:"expires_in"`
}

//获取小程序全局唯一后台接口调用凭据
func AccessToken(AppID string ,AppSecret string) (interface{},error){
	url:="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"+"&appid="+AppID+"&secret="+AppSecret
	var data interface{}
	err:=shttps.New(url).Res(&data).Get()
	if err!=nil {
		return nil, err
	}
	return data ,nil
}

//检查一段文本是否含有违法违规内容
func MsgSecCheck(AppID string ,AppSecret string,req *CheckStructReq)(interface{},error){
	//获取凭证
	data,err:=AccessToken(AppID,AppSecret)
	if err!=nil {
		return nil, err
	}
	//转换
	tokennew:=new(AccessTokenRes)
	bs,err:=json.Marshal(data)
	err=json.Unmarshal(bs,&tokennew)
	if err!=nil {
		return nil,err
	}

	if err!=nil {
		return nil, err
	}

	url:="https://api.weixin.qq.com/wxa/msg_sec_check?access_token="+tokennew.AccessToken

	req.Version="2"
	//check判断返回值
	var newdata interface{}
	err=shttps.New(url).Req(req).Res(&newdata).Post()
	if err!=nil {
		return nil, err
	}

	return newdata,nil
}
